import React, { useState } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Upload,
  message,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Tree,
  Row,
  Col,
  Typography,
  Tooltip,
  Progress,
  Spin,
} from "antd";
import {
  UploadOutlined,
  FolderOutlined,
  FileOutlined,
  DeleteOutlined,
  EditOutlined,
  DownloadOutlined,
  ShareAltOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  EyeOutlined,
} from "@ant-design/icons";
import type { UploadProps, UploadFile } from "antd";
import type { DataNode } from "antd/es/tree";
import styled from "styled-components";
import type { TableRowSelection } from "antd/es/table/interface";
import type { Key } from "react";

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { DirectoryTree } = Tree;
const { confirm } = Modal;

// 类型定义
interface Resource {
  id: string;
  name: string;
  type: "ppt" | "pdf" | "doc" | "folder";
  size: string;
  uploadTime: string;
  category: "课件" | "实验资料" | "试题资料";
  downloads: number;
  shared: boolean;
  description?: string;
  progress?: number;
}

interface TreeNode extends DataNode {
  title: string;
  key: string;
  children?: TreeNode[];
  isLeaf?: boolean;
}

interface FormValues {
  name: string;
  category: Resource["category"];
  description?: string;
}

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const ResourceIcon = styled.span<{ type: Resource["type"] }>`
  .anticon {
    font-size: 16px;
    margin-right: 8px;
    color: ${(props) => {
      switch (props.type) {
        case "ppt":
          return "#FF9900";
        case "pdf":
          return "#FF0000";
        case "doc":
          return "#0066CC";
        case "folder":
          return "#666666";
        default:
          return "#999999";
      }
    }};
  }
`;

const TeacherResources: React.FC = () => {
  const [resources, setResources] = useState<Resource[]>([
    {
      id: "1",
      name: "嵌入式系统导论.pptx",
      type: "ppt",
      size: "2.5MB",
      uploadTime: "2024-03-15",
      category: "课件",
      downloads: 25,
      shared: true,
    },
    {
      id: "2",
      name: "实验指导书.pdf",
      type: "pdf",
      size: "1.8MB",
      uploadTime: "2024-03-16",
      category: "实验资料",
      downloads: 30,
      shared: true,
    },
    {
      id: "3",
      name: "期中考试试题.docx",
      type: "doc",
      size: "500KB",
      uploadTime: "2024-03-17",
      category: "试题资料",
      downloads: 0,
      shared: false,
    },
  ]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedResource, setSelectedResource] = useState<string | null>(null);
  const [form] = Form.useForm();

  const [uploadingFiles, setUploadingFiles] = useState<{
    [key: string]: number;
  }>({});
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);

  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewResource, setPreviewResource] = useState<Resource | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      if (selectedResource) {
        // 编辑现有资源
        setResources(
          resources.map((r) =>
            r.id === selectedResource ? { ...r, ...values } : r
          )
        );
        message.success("资源更新成功！");
      } else {
        // 添加新资源
        setResources([
          ...resources,
          {
            ...values,
            id: Date.now().toString(),
            size: "0KB",
            uploadTime: new Date().toISOString().split("T")[0],
            downloads: 0,
            shared: false,
          },
        ]);
        message.success("资源添加成功！");
      }
      setIsModalVisible(false);
      form.resetFields();
      setSelectedResource(null);
    } catch (error) {
      console.error("Validation failed:", error);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
    setSelectedResource(null);
  };

  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: "删除后将无法恢复，是否确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        setResources(resources.filter((r) => r.id !== id));
        message.success("删除成功");
      },
    });
  };

  const handleShare = (id: string) => {
    setResources(
      resources.map((r) => (r.id === id ? { ...r, shared: !r.shared } : r))
    );
    message.success("分享状态已更新");
  };

  const uploadProps: UploadProps = {
    name: "file",
    action: "/api/upload",
    headers: {
      authorization: "authorization-text",
    },
    multiple: true,
    directory: false,
    showUploadList: false,
    progress: {
      strokeColor: {
        "0%": "#108ee9",
        "100%": "#87d068",
      },
      strokeWidth: 3,
      format: (percent) => `${percent}%`,
    },
    beforeUpload: (file) => {
      // 检查文件类型
      const isValidType = [
        "application/pdf",
        "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      ].includes(file.type);
      if (!isValidType) {
        message.error("只支持 PDF、PPT、Word 格式的文件！");
        return false;
      }
      // 检查文件大小（限制为50MB）
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!isLt50M) {
        message.error("文件大小不能超过 50MB！");
        return false;
      }
      return true;
    },
    onChange(info) {
      const { status, name, uid, percent } = info.file;

      // 更新上传进度
      setUploadingFiles((prev) => ({
        ...prev,
        [uid]: percent || 0,
      }));

      if (status === "done") {
        message.success(`${name} 文件上传成功`);
        // 添加新资源到列表
        const newResource: Resource = {
          id: uid,
          name,
          type: name.split(".").pop() as Resource["type"],
          size: `${(info.file.size! / 1024 / 1024).toFixed(2)}MB`,
          uploadTime: new Date().toISOString().split("T")[0],
          category: (selectedCategory as Resource["category"]) || "课件",
          downloads: 0,
          shared: false,
        };
        setResources((prev) => [...prev, newResource]);
        // 清除进度
        setUploadingFiles((prev) => {
          const { [uid]: _, ...rest } = prev;
          return rest;
        });
      } else if (status === "error") {
        message.error(`${name} 文件上传失败`);
        // 清除进度
        setUploadingFiles((prev) => {
          const { [uid]: _, ...rest } = prev;
          return rest;
        });
      }
    },
  };

  const draggerProps: UploadProps = {
    ...uploadProps,
    style: {
      marginBottom: 16,
      display: selectedRowKeys.length > 0 ? "none" : "block",
    },
  };

  const treeData = [
    {
      title: "课件",
      key: "0-0",
      children: [
        { title: "第一章：绪论", key: "0-0-0" },
        { title: "第二章：嵌入式系统基础", key: "0-0-1" },
        { title: "第三章：嵌入式系统硬件", key: "0-0-2" },
      ],
    },
    {
      title: "实验资料",
      key: "0-1",
      children: [
        { title: "实验一：开发环境搭建", key: "0-1-0" },
        { title: "实验二：GPIO编程", key: "0-1-1" },
        { title: "实验三：中断实验", key: "0-1-2" },
      ],
    },
    {
      title: "试题资料",
      key: "0-2",
      children: [
        { title: "练习题", key: "0-2-0" },
        { title: "期中考试", key: "0-2-1" },
        { title: "期末考试", key: "0-2-2" },
      ],
    },
  ];

  const columns = [
    {
      title: "资源名称",
      dataIndex: "name",
      key: "name",
      render: (text: string, record: Resource) => (
        <Space>
          <ResourceIcon type={record.type}>
            <FileOutlined />
          </ResourceIcon>
          <Text>{text}</Text>
          {uploadingFiles[record.id] !== undefined && (
            <Progress percent={uploadingFiles[record.id]} size="small" />
          )}
        </Space>
      ),
    },
    {
      title: "分类",
      dataIndex: "category",
      key: "category",
      render: (category: string) => <Tag color="blue">{category}</Tag>,
    },
    {
      title: "大小",
      dataIndex: "size",
      key: "size",
    },
    {
      title: "上传时间",
      dataIndex: "uploadTime",
      key: "uploadTime",
    },
    {
      title: "下载次数",
      dataIndex: "downloads",
      key: "downloads",
    },
    {
      title: "分享状态",
      dataIndex: "shared",
      key: "shared",
      render: (shared: boolean) => (
        <Tag color={shared ? "green" : "default"}>
          {shared ? "已分享" : "未分享"}
        </Tag>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Resource) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handlePreview(record)}
          >
            预览
          </Button>
          <Button
            type="link"
            icon={<DownloadOutlined />}
            onClick={() => handleDownload(record)}
          >
            下载
          </Button>
          <Button
            type="link"
            icon={<ShareAltOutlined />}
            onClick={() => handleShare(record.id)}
          >
            {record.shared ? "取消分享" : "分享"}
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => {
              setSelectedResource(record.id);
              form.setFieldsValue(record);
              setIsModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleDownload = async (record: Resource) => {
    try {
      // 这里应该调用实际的下载 API
      message.loading({ content: "准备下载...", key: record.id });

      // 模拟下载过程
      await new Promise((resolve) => setTimeout(resolve, 1500));

      // 更新下载次数
      setResources((prev) =>
        prev.map((r) =>
          r.id === record.id ? { ...r, downloads: r.downloads + 1 } : r
        )
      );

      message.success({ content: "下载成功", key: record.id });

      // 实际下载逻辑
      const link = document.createElement("a");
      link.href = `/api/download/${record.id}`;
      link.download = record.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      message.error({ content: "下载失败，请重试", key: record.id });
    }
  };

  const handlePreview = async (record: Resource) => {
    setPreviewVisible(true);
    setPreviewResource(record);
    setPreviewLoading(true);

    try {
      // 这里应该调用实际的预览 API
      await new Promise((resolve) => setTimeout(resolve, 1000));
      setPreviewLoading(false);
    } catch (error) {
      message.error("文件预览加载失败");
      setPreviewLoading(false);
    }
  };

  // 批量操作处理
  const handleBatchDelete = () => {
    confirm({
      title: `确认删除选中的 ${selectedRowKeys.length} 个文件？`,
      icon: <ExclamationCircleOutlined />,
      content: "删除后将无法恢复",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        setResources((prev) =>
          prev.filter((item) => !selectedRowKeys.includes(item.id))
        );
        setSelectedRowKeys([]);
        message.success("批量删除成功");
      },
    });
  };

  const handleBatchShare = () => {
    setResources((prev) =>
      prev.map((item) =>
        selectedRowKeys.includes(item.id) ? { ...item, shared: true } : item
      )
    );
    message.success("批量分享成功");
    setSelectedRowKeys([]);
  };

  const rowSelection: TableRowSelection<Resource> = {
    selectedRowKeys,
    onChange: (selectedKeys: Key[], selectedRows: Resource[]) => {
      setSelectedRowKeys(selectedKeys);
    },
  };

  return (
    <div>
      <Row gutter={24}>
        <Col span={6}>
          <StyledCard title="资源目录">
            <DirectoryTree
              defaultExpandAll
              treeData={treeData}
              onSelect={(_, { node }) => {
                setSelectedCategory((node as TreeNode).title);
              }}
            />
          </StyledCard>
        </Col>
        <Col span={18}>
          <StyledCard
            title={
              <Space>
                <span>资源列表</span>
                {selectedRowKeys.length > 0 && (
                  <Tag color="blue">{`已选择 ${selectedRowKeys.length} 项`}</Tag>
                )}
              </Space>
            }
            extra={
              <Space>
                {selectedRowKeys.length > 0 ? (
                  <>
                    <Button
                      icon={<ShareAltOutlined />}
                      onClick={handleBatchShare}
                    >
                      批量分享
                    </Button>
                    <Button
                      danger
                      icon={<DeleteOutlined />}
                      onClick={handleBatchDelete}
                    >
                      批量删除
                    </Button>
                  </>
                ) : (
                  <>
                    <Upload {...uploadProps}>
                      <Button icon={<UploadOutlined />}>上传资源</Button>
                    </Upload>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={showModal}
                    >
                      新建文件夹
                    </Button>
                  </>
                )}
              </Space>
            }
          >
            <Upload.Dragger {...draggerProps}>
              <p className="ant-upload-drag-icon">
                <UploadOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持单个或批量上传，严禁上传违规文件
              </p>
            </Upload.Dragger>

            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={resources}
              rowKey="id"
            />
          </StyledCard>
        </Col>
      </Row>

      <Modal
        title={selectedResource ? "编辑资源" : "新建文件夹"}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: "请输入名称" }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: "请选择分类" }]}
          >
            <Select placeholder="请选择分类">
              <Option value="课件">课件</Option>
              <Option value="实验资料">实验资料</Option>
              <Option value="试题资料">试题资料</Option>
            </Select>
          </Form.Item>
          <Form.Item name="description" label="描述">
            <TextArea rows={4} placeholder="请输入描述信息" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={previewResource?.name}
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={1000}
        style={{ top: 20 }}
        bodyStyle={{ height: "calc(100vh - 200px)", padding: 0 }}
      >
        {previewLoading ? (
          <div style={{ textAlign: "center", padding: "40px 0" }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>加载预览...</div>
          </div>
        ) : (
          <iframe
            src={`/api/preview/${previewResource?.id}`}
            style={{
              width: "100%",
              height: "100%",
              border: "none",
            }}
            title="文件预览"
          />
        )}
      </Modal>
    </div>
  );
};

export default TeacherResources;
